package sqlite

import (
	"LinkWareHouse/errhandle"
	"LinkWareHouse/storage"
	"database/sql"
	"fmt"

	_ "github.com/mattn/go-sqlite3"
)

type Storage struct {
	db *sql.DB
}

func (s *Storage) Init() error {
	q := `CREATE TABLE IF NOT EXISTS pages (Name TEXT, Link TEXT NOT NULL UNIQUE, DelAfterViewing BOOLEAN)`
	_, err := s.db.Exec(q)
	return errhandle.CheckError("can't create table", err)
}

func New(path string) (*Storage, error) {
	db, err := sql.Open("sqlite3", path)
	return &Storage{db: db}, errhandle.CheckError("can't open page", err)
}

func (s *Storage) Save(p *storage.Page) error {
	q := `INSERT INTO pages (Name, Link, DelAfterViewing) VALUES (?,?,?)`
	_, err := s.db.Exec(q, p.Name, p.Link, p.DelAfterViewing)
	return errhandle.CheckError("can't save page", err)
}

func (s *Storage) PickRandom() (*storage.Page, error) {
	var (
		Name, Link      string
		DelAfterViewing bool
	)
	q := `SELECT * FROM pages ORDER BY RANDOM() LIMIT 1`
	err := s.db.QueryRow(q).Scan(&Name, &Link, &DelAfterViewing)
	if err == sql.ErrNoRows {
		return nil, err
	}
	return &storage.Page{Name: Name, Link: Link, DelAfterViewing: DelAfterViewing}, errhandle.CheckError("can't pick random page", err)
}

func (s *Storage) Remove(p *storage.Page) error {
	q := `DELETE FROM pages WHERE Name = ? AND Link = ?`
	_, err := s.db.Exec(q, p.Name, p.Link)
	return errhandle.CheckError("can't remove page", err)
}

func (s *Storage) GetRow() []string {
	var (
		Name, Link, DelAfterViewing string
		row                         []string
	)
	q := `SELECT * FROM pages`
	rows, err := s.db.Query(q)
	for rows.Next() {
		rows.Scan(&Name, &Link, &DelAfterViewing)
		str := fmt.Sprint(Name, " ", Link, " ", DelAfterViewing)
		row = append(row, str)
	}
	errhandle.CheckError("can't get row from page", err)
	return row
}
